package com.hxalex.simulationhandle.accessbilityService.receiver.wifi;

import android.content.Intent;
import android.util.Log;
import android.view.accessibility.AccessibilityNodeInfo;

import com.hxalex.simulationhandle.accessbilityService.command.base.BaseCommand;
import com.hxalex.simulationhandle.accessbilityService.command.wifi.CheckWifiIsConnectCommand;
import com.hxalex.simulationhandle.accessbilityService.command.wifi.ConnectWifiCommand;
import com.hxalex.simulationhandle.accessbilityService.command.wifi.SearchWifiCommand;
import com.hxalex.simulationhandle.accessbilityService.manger.CommandManger;
import com.hxalex.simulationhandle.accessbilityService.manger.SearchManger;
import com.hxalex.simulationhandle.accessbilityService.manger.WifiManger;
import com.hxalex.simulationhandle.accessbilityService.model.WifiInfoBean;
import com.hxalex.simulationhandle.accessbilityService.receiver.base.BaseReceiver;
import com.hxalex.simulationhandle.accessbilityService.receiver.wifi.service.WifiInfoService;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * Created by hx_Alex on 2018/5/27.
 */

public class ConnectWifiReceiver extends BaseReceiver {
    public static final int TYPE_CLICK = 1;
    public static final int TYPE_BACK = 2;
    private static final String TAG = "ConnectWifiReceiver";
    private ArrayList<WifiInfoBean> wifiInfoBeanArrayList;
    private AccessibilityNodeInfo rootNodeInfo;
    private onClickItemListener onClickItemListener;
    private AccessibilityNodeInfo connectNode;
    public boolean isBackDialog=false;
    public ConnectWifiReceiver(WifiManger wifiManger) {
        super(wifiManger);
        FLAG="连接wifi命令";
    }

    public void setRootNodeInfo(AccessibilityNodeInfo rootNodeInfo) {
        this.rootNodeInfo = rootNodeInfo;
    }


    public void setOnClickItemListener(ConnectWifiReceiver.onClickItemListener onClickItemListener) {
        this.onClickItemListener = onClickItemListener;
    }

    @Override
    public void doSomething() {
        if(!isPrintCommandMsg)
        {
            Log.w("ConnectWifiReceiver","开始执行"+FLAG);
            isPrintCommandMsg=true;
        }
        wifiInfoBeanArrayList = wifiManger.getWifiInfoBeanArrayList();
      
        if (wifiInfoBeanArrayList.size() == 0) 
        {
            Log.i(TAG,"wifi列表为空");
            return;
        }
//        int nowWifiIndex = wifiManger.nowWifiIndex;
        if (wifiManger.getWifiInfoBeanArrayList().size()!=0) {
            WifiInfoBean wifiInfoBean = wifiInfoBeanArrayList.get(0);
            String wifiName = wifiInfoBean.getWifiName();
            if (wifiName.contains("CMCC") || wifiName.contains("JSU") || wifiName.contains("China")) {
                Log.e(TAG, wifiName + "属于需要网页认证的wifi 跳过");
                wifiManger.getConnectedWifiList().add(wifiInfoBean);
                CommandManger commandManger=CommandManger.getManger();
                ArrayBlockingQueue<BaseCommand> commandQueue = commandManger.getCommandQueue();
                commandQueue.offer(new SearchWifiCommand(wifiManger, new SearchWifiReceiver(wifiManger)));
                commandQueue.offer(new ConnectWifiCommand(wifiManger, new ConnectWifiReceiver(wifiManger)));
                commandCompleteListener.commandCompleteListener();
                return;
            }
            
            AccessibilityNodeInfo itemInfo = wifiInfoBean.getItemInfo();//获取一条wifi Item
            //点击成功
            if (itemInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK)) {
                Timer timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        //延迟获取
                        onClickItemListener.onclickItem(TYPE_CLICK);
                        AccessibilityNodeInfo wifiAppRootInfo = wifiManger.getWifiAppRootInfo();
                        recycle(wifiAppRootInfo,wifiInfoBean);
                        if (connectNode != null ) {
                            Log.e(TAG, "开始尝试连接wifi " + wifiInfoBean.getWifiName());
                            connectNode.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                            wifiManger.getConnectedWifiList().add(wifiInfoBean);
//                            wifiManger.nowWifiIndex+=1;
                            CommandManger manger=CommandManger.getManger();
                            ArrayBlockingQueue<BaseCommand> commandQueue = manger.getCommandQueue();
                            commandQueue.offer(new CheckWifiIsConnectCommand(wifiManger, new CheckWifiIsConnectReceiver(wifiManger)));
                        } else if (wifiManger.isWifi())//已经连接wifi 
                        {
                            Log.e(TAG, "已经连接wifi，连接wifi名:" + wifiInfoBean.getWifiName());
                            if (!isBackDialog) {
                                onClickItemListener.onclickItem(TYPE_BACK);
                                isBackDialog = true;
//                                wifiManger.nowWifiIndex += 1;
                                wifiManger.getConnectedWifiList().add(wifiInfoBean);
                                Intent i = new Intent(WifiManger.getContext(), WifiInfoService.class);
                                i.setAction(WifiInfoService.WIFI_PING);
                                WifiManger.getContext().startService(i);
                            }
                        }else if(connectNode==null)
                        {
                            Log.e(TAG,"目标按钮为空，重新执行命令");
                            EventBus.getDefault().post(SearchManger.OPEN_WAKE_WINWODS);
                            CommandManger.getManger().getCommandQueue().clear();
                            wifiManger.loadAllWifiCommand();
                        }
                    }
                }, 2000);

            }else
            {
                wifiManger.loadAllWifiCommand();
            }
            nowItemWifiName="";
            commandCompleteListener.commandCompleteListener();
            
        }
    }
    private String nowItemWifiName="";
    private void recycle(AccessibilityNodeInfo info,WifiInfoBean wifiInfoBean) {
        if(info==null) return;
        if (info.getChildCount() == 0) {
//            Log.e(TAG, info.toString());
            String msg = info.getText() != null ? info.getText().toString() : "";
            if (info.getClassName()!=null &&info.getClassName().equals("android.widget.TextView") && info.getViewIdResourceName() != null
                    && info.getViewIdResourceName().equals("com.snda.wifilocating:id/alertTitle") && info.getText()!=null) 
            {
               String wifiTitle= info.getText().toString();
                Log.i(TAG,"当前点击打开的wifi连接弹窗 wifi名为:"+wifiTitle);
             if(!wifiInfoBean.getWifiName().equals(wifiTitle))
             {
                 Log.e(TAG,"当前点击打开的wifi连接弹窗与需要连接的wifi名不匹配重新检索wifi");
                 if (!isBackDialog) {
                     onClickItemListener.onclickItem(TYPE_BACK);
                     isBackDialog=true;
                 }
                 CommandManger manger=CommandManger.getManger();
                 ArrayBlockingQueue<BaseCommand> commandQueue = manger.getCommandQueue();
                 commandQueue.offer(new SearchWifiCommand(wifiManger, new SearchWifiReceiver(wifiManger)));
                 commandQueue.offer(new ConnectWifiCommand(wifiManger, new ConnectWifiReceiver(wifiManger)));
                 commandCompleteListener.commandCompleteListener();
                 return;
             }
                Log.i(TAG,"当前点击打开的wifi连接弹窗与需要连接的wifi名匹配，检索连接按钮信息");

            }
            if (info.getClassName().equals("android.widget.TextView") && info.getViewIdResourceName() == null) {
//                if(!nowItemWifiName.contains(wifiInfoBean.getWifiName())) return;
                if (msg.equals("直接连接") || msg.equals("钥匙连接")) {
                    connectNode = info;
                    return;
                } 
                
            }

        } else {
//            Log.i(TAG, info.toString());
            for (int i = 0; i < info.getChildCount(); i++) {
                if (info.getChild(i) != null) {
                    recycle(info.getChild(i),wifiInfoBean);
                }
            }
        }
    }


    public interface onClickItemListener {
        void onclickItem(int EventType);
    }
}
